<template>
	<view class="update-version-container">
		<view class="container" v-show='showVersionModel'>
			<view class="content">
				<view class="header">
					<image src="/static/update.png" mode=""></image>
				</view>
				<view class="body">
					<text class="body-header">发现新版本 (v.{{ version }})</text>
					<view class="body-text">
						<text class="version-text">{{content}}</text>
					</view>
				</view>
				<view class="btn-wrap" v-if="!showPro">
					<text class="confirm-btn" @click="handleConfirmUpdate">立即下载更新</text>

				</view>
				<view class="probox" v-else>
					<progress :percent="value" show-info border-radius="50" />
				</view>
				<!-- <view class="cancel-btn-wrap"  v-if="!showPro">
					<text class="cancel-btn" name='close' color='#fff' size="40" @click="handleCancel">x</text>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "updateVerison",
		props: {

			// 是否启动校验更新
			hasValidUpdate: {
				type: Boolean,
				default: () => true,

			}
		},
		data() {
			return {
				content: "1.更新最新版本;\n2.版本优化;",
				version: "1.4.1",
				showVersionModel: false,
				dtask: null,
				curVersionInfo: {},
				showPro: false,
				value: 0
			}
		},
		created() {
			// #ifdef APP-PLUS
			this.hasValidUpdate && this.checkHasUpdateVersion();
			// #endif
		},
		methods: {
			/*
			 * 版本号比较方法
			 * 传入两个字符串，当前版本号：curV；比较版本号：reqV
			 * 调用方法举例：compare("1.1","1.2")，将返回false
			 */
			compare(curV, reqV) {
				if (curV && reqV) {
					//将两个版本号拆成数字
					var arr1 = curV.split('.'),
						arr2 = reqV.split('.');
					var minLength = Math.min(arr1.length, arr2.length),
						position = 0,
						diff = 0;
					//依次比较版本号每一位大小，当对比得出结果后跳出循环（后文有简单介绍）
					while (position < minLength && ((diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0)) {
						position++;
					}
					diff = (diff != 0) ? diff : (arr1.length - arr2.length);
					//若curV大于reqV，则返回true
					return diff > 0;
				} else {
					//输入为空
					console.log("版本号不能为空");
					return false;
				}
			},
			// 检查是否需要进行更新
			checkHasUpdateVersion() {
				uni.getSystemInfo({
					success: (res) => {
						if (res.platform == "android") {
							plus.runtime.getProperty(plus.runtime.appid, (inf) => {
								this.curVersionInfo.wgtVer = inf.version; //获取当前版本号
								this.curVersionInfo.version = plus.runtime.version;
								// this.showVersionModel = true;
								this.androidCheckUpdate();
							});

						}
					}
				})
			},
			// 版本对比
			androidCheckUpdate() {
				// 根据接口返回处理；
				uni.request({
					url: getApp().globalData.data.requestUrl + '/Api/ApkVersion',
					success: (res) => {
						this.version = res.data.data.version;
						if (res.data.data.content != '') {
							this.content = res.data.data.content
						}
						let down_url = res.data.data.down_url;
						var check = this.compare(this.version, this.curVersionInfo.wgtVer);
						if (check) {
							this.showVersionModel = true;
							this.dtask = plus.downloader.createDownload(down_url, {},
								(
									d, status) => {
									// 下载完成  
									if (status == 200) {
										plus.runtime.install(plus.io.convertLocalFileSystemURL(d
												.filename), {}, {},
											(error) => {
												this.$showToast("安装失败")
											})
									} else {
										this.$showToast("更新失败")
									}
									uni.hideLoading();
								});
						}
					}
				})
				// getAppVersionInfo().then(res => {
				// 	this.content = res.data.note,

				// }).catch(err => {
				// 	console.log("err", JSON.stringify(err));
				// })
			},
			handleConfirmUpdate() {
				console.log("confirm update");
				this.showPro = true
				// this.showVersionModel = false;
				// uni.showLoading({
				// 	title: "下载更新中",
				// 	mask: true,
				// });
				// this.dtask.start();
				var _this = this
				try {
					this.dtask.start(); // 开启下载的任务
					var prg = 0;
					var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 

					this.dtask.addEventListener('statechanged', function(task, status) {
						console.log('自动更新测试1：', task)
						console.log('自动更新测试2：', status)
						// 给下载任务设置一个监听 并根据状态  做操作
						switch (task.state) {
							case 1:
								// showLoading.setTitle("正在下载");
								break;
							case 2:
								// showLoading.setTitle("已连接到服务器");
								break;
							case 3:
								prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) *
									100);
								// showLoading.setTitle("  正在下载" + prg + "%  ");
								_this.value = prg
								break;
							case 4:
								plus.nativeUI.closeWaiting();
								//下载完成
								break;
						}
					});
				} catch (err) {
					console.log('错误信息', err)
					plus.nativeUI.closeWaiting();
				}
			},
			// 取消
			handleCancel() {
				this.showVersionModel = false;
			}
		}
	}
</script>

<style scoped lang="scss">
	$bgColor: #4e5ae0;

	.probox {
		padding: 30rpx;
		height: 88rpx;
		line-height: 88rpx;
		background-color: $bgColor;
		position: relative;
		border-bottom-left-radius: 30rpx;
		border-bottom-right-radius: 30rpx;
		color: #FFFFFF;
	}

	.update-version-container {
		.container {
			position: fixed;
			left: 0;
			top: 0;
			width: 100vw;
			height: 100vh;
			background-color: rgba($color: #000000, $alpha: .6);
			z-index: 99999;
		}

		.content {
			// border: 1px solid #FFFFFF;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			width: 75vw;
			border-radius: 30rpx;
			box-sizing: border-box;
			background-color: transparent;


			.header {
				width: 100%;
				position: relative;
				box-sizing: border-box;
				padding: 0;
				margin: 0;
				height: auto;
				margin-top: -30%;
				background-color: transparent;

				image {
					width: 100%;
					height: 350rpx;
					margin: 0;
					/* #ifdef APP-PLUS */
					margin-top: -70rpx;
					/* #endif */
				}

				&::before {
					content: "";
					width: 100%;
					height: 100%;
					position: absolute;
					top: 25%;
					/* #ifdef APP-PLUS */
					top: 0;
					/* #endif */
					left: 0px;
					background-color: $bgColor;
					border-radius: 30rpx;
					z-index: -1;
				}

				&::after {
					content: "";
					display: inline-block;
					width: 100%;
					position: absolute;
					height: 30rpx;
					bottom: -2px;
					z-index: 9;
					left: 0;
					background-color: #FFFFFF;
				}
			}

			.body {
				margin: 0;
				width: 100%;
				min-height: 200rpx;
				background: #FFFFFF;
				padding: 0px;
				position: relative;
				box-sizing: border-box;
				/* #ifdef APP-PLUS */
				margin-top: 38px;
				/* #endif */

				&::before {
					content: "";
					background-color: #FFFFFF;
					position: absolute;
					width: 100%;
					left: 0;
					top: -2rpx;
					height: 2px;
				}

				.body-header {
					font-weight: bolder;
					font-size: 32rpx;
					padding: 0 30rpx;
				}

				.body-text {
					padding: 10px 30rpx;
					width: 90%;
					word-break: break-all;

					.version-text {
						font-size: 26rpx;

					}
				}

			}

			.btn-wrap {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 30rpx;
				background-color: $bgColor;
				position: relative;
				border-bottom-left-radius: 30rpx;
				border-bottom-right-radius: 30rpx;

				&::after {
					content: "";
					display: inline-block;
					width: 100%;
					height: 20rpx;
					position: absolute;
					top: -5px;
					background-color: $bgColor;
					border-radius: 200%;
				}

				.confirm-btn {
					padding: 15rpx 40rpx;
					font-size: 36rpx;
					color: #FFFFFF;
					border-radius: 50rpx;
					border: 1px solid #FFFFFF;
				}
			}

			.cancel-btn-wrap {
				text-align: center;
				width: 100%;
				position: absolute;
				display: flex;
				justify-content: center;
				align-items: center;
				bottom: 0;
				left: 0;
				transform: translateY(150%);

				.cancel-btn {
					display: block;
					border: 2px solid #FFFFFF;
					border-radius: 50%;
					padding: 10rpx;
					color: #ffffff;
					width: 20px;
					height: 20px;
					font-weight: bold;
					line-height: 20px;
					text-align: center;
				}
			}
		}
	}
</style>>
